<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api;

use App\Http\Services\LoginService;
use App\Models\Printer;
use App\Models\Supplier;
use App\Models\User\User;
use App\Repositories\Api\DailyMenuRepository;
use App\Repositories\Api\ShopRepository;
use App\Repositories\Manage\StallRepository;
use App\Repositories\OrderRepository;
use App\Repositories\PrinterRepository;

class ShopConsoleController extends MiniAppController
{

    private $shopRepo = NULL,
        $orderRepo = NULL;

    public function __construct(
        ShopRepository  $shopRepo,
        OrderRepository $orderRepo
    )
    {
        parent::__construct();
        $this->shopRepo = $shopRepo;
        $this->orderRepo = $orderRepo;
    }

    /**
     *
     */
    public function login()
    {
        $username = request()->post("username", "");
        $password = request()->post("password", "");

        if (empty($username))
            return retFail("用户名不能为空");

        if (empty($password))
            return retFail("密码不能为空");

        $loginService = new LoginService();

        try {
            $user = $loginService->shopLogin($username, $password);
            $token = $loginService->authcode($user['id'], 'ENCODE');
            $shop_type = Supplier::query()->where(['id' => $user['shop_id']])->value("type");

            return retSuc([
                'accessToken' => $token,
                'tokenType' => "shop",
                'username' => $username,
                'shop_type' => $shop_type ?? 0
            ]);

        } catch (\Exception $e) {
            return retFail($e->getMessage());
        }
    }

    /**
     * 店铺订单
     */
    public function order_list()
    {
        $filter = $this->_filter();

        if ($filter['shop_type'] == 1 && (empty($filter['menu_id']) || count($filter['menu_id']) == 0)) {
            return retSuc([
                "items" => [],
                "total" => 0,
                "current_page" => 1,
                "last_page" => 1,
            ]);
        }

        $res = (new OrderRepository())->getShopOrderList($filter, $this->pageNum, $this->pageSize);
        return retSuc($res);
    }

    /**
     * 确认已出餐
     */
    public function confirm_deliver()
    {
        $filter = $this->_filter();

        if (count($filter['ids']) == 1 && !empty($filter['menu_id'])) {
            unset($filter['menu_id']);
        }

        $orderIds = $this->orderRepo->getStat($filter, 2);

        if (empty($orderIds))
            return retSuc([], "没有符合条件的接单");

        $res = $this->orderRepo->adminUpdateOrder($orderIds, [
            'delivery_status' => 20,
            'deliver_status' => 2
        ]);

        if ($res) {
            $this->orderRepo->addLog($orderIds, 2, UID);
        }

        return retSuc([], "已确认出餐(" . count($orderIds) . ")单");
    }

    /**
     * 确认接单
     */
    public function accept()
    {
        $filter = $this->_filter();
        if (count($filter['ids']) == 1 && !empty($filter['menu_id'])) {
            unset($filter['menu_id']);
        }

        $orderIds = $this->orderRepo->getStat($filter, 2);
        if (empty($orderIds))
            return retFail("没有符合条件的接单");

        $res = $this->orderRepo->adminUpdateOrder($orderIds, ['delivery_status' => 10]);
        if ($res) {
            $this->orderRepo->addLog($orderIds, 1, UID);
        }

        return retSuc([], "已接单(" . count($orderIds) . ")单");
    }

    /**
     * 打印初始化数据
     */
    public function printer_init_data()
    {
        $filter = $this->_filter();
        if ($filter['shop_type'] == 0 && $filter['menu_id']) {
            unset($filter['menu_id']);
        }

        $printers = (new PrinterRepository())->getOptions(intval($filter['shop_id']), $filter['printer_type'] == 'label' ? 2 : 1);
        if ($filter['printer_type'] == 'label') { //品单
            $stalls = $this->orderRepo->getOrderStalls($filter);
        }

        if ($filter['printer_type'] == 'stall') {
            $data = $this->orderRepo->getOrderStallStat($filter);
            $total_product = array_sum(get_column($data, 'amount'));
            $orderIds = $this->orderRepo->getOrderIdsByOrderProduct($filter);
            $total_order = count($orderIds);
        } else {
            $data = $this->orderRepo->getOrderStat($filter);
            $total_product = array_sum(get_column($data, 'product_amount'));
            $total_order = array_sum(get_column($data, 'order_amount'));
        }

        return retSuc([
            'stalls' => $stalls ?? null,
            'printers' => $printers,
            'statList' => $data,
            'total_product' => $total_product ?? 0,
            'total_order' => $total_order ?? 0,
//            'currentDate' => date("m/d", strtotime($filter['date']))
        ]);
    }

    /**
     * 打印数据
     */
    public function printer()
    {
        $params = request()->all();
        $printer_type = $params['printer_type'] ?? "";

        $printer = Printer::query()->where(['id' => intval($params['printer_id']), 'status' => 1])->first();
        if (empty($printer))
            return retFail("打印机不存在,请检查打印机是否设置");

        /*
        if ($printer_type == 'label' && $printer['type'] != 2) {
            return retFail("请选择标签打印机");
        }*/
        $filter = $this->_filter();
        if ($printer['shop_id'] != SHOP_ID)
            return retFail("非法操作");

        if (empty($filter['stall_id'])) {
            $filter['stall_id'] = (new StallRepository())->getIdsByShopId(SHOP_ID);
        }

        if ($printer_type == 'label') { //标签打印
            return (new  PrinterRepository())->printerLabel($filter, intval($printer['id']));
        } else if ($printer_type == 'order') { //打印订单
            return $this->orderRepo->printerOrder($filter, intval($printer['id']));
        } else if ($printer_type == 'stall') { //档口
            return $this->orderRepo->printerStall($filter, intval($printer['id']));
        } else if ($printer_type == 'keshi') { //科室  ToDo : 待处理
            $data = $this->orderRepo->getOrderStat($filter);
        } else {
            return retFail("打印类型不存在");
        }

    }

    /**
     * 查询条件
     */
    public function _filter()
    {
        $params = request()->all();
        $filter = [];

        $m_filter['date'] = trim(str_replace(".", "-", $params['current_date']));
        if ($m_filter['date']) {
            $m_filter['date'] = date("Y-m-d", strtotime($m_filter['date']));
        }

        if ($params['menu_type'] > 0) {
            $m_filter['type'] = intval($params['menu_type']) - 1;
        } else {
            $filter['current_date'] = $m_filter['date'];
        }
        $filter['menu_id'] = (new DailyMenuRepository())->getMenuIds($m_filter);
        if (!empty($params['stall_id'])) {
            $filter['stall_id'] = $params['stall_id'];
        }

        if ($params["ids"]) {
            if (is_array($params["ids"])) {
                $filter['ids'] = $params['ids'];
            } else {
                $filter['ids'] = array_filter(explode("-", $params["ids"]));
            }
        }

        $params['status'] && $filter['status'] = intval($params['status']);
        !empty($params['printer_type']) && $filter['printer_type'] = $params['printer_type'];
        $filter['shop_id'] = SHOP_ID;
        if ($filter['shop_id']) {
            $filter['shop_type'] = Supplier::query()->where("id", $filter['shop_id'])->value("type");

            //单店不查询菜单
            if ($filter['shop_type'] == 0 && $filter['menu_id']) {
                unset($filter['menu_id']);
            }
        }
        intval($params['deliver_time']) && $filter['deliver_time'] = $params['deliver_time'];
        return $filter;
    }

    /**
     * 店铺统计
     */
    public function stat()
    {
        $res = $this->orderRepo->getConsoleShopStat(SHOP_ID);
//        $res = $this->orderRepo->consoleOrderStat(SHOP_ID);
        return retSuc($res);
    }

    /**
     * 修改密码
     */
    public function reset_password()
    {
        $password = request()->post("password");
        $password2 = request()->post("password2");

        if (empty($password))
            return retFail("新密码不能为空");

        if ($password != $password2) {
            return retFail("两次输入的新密码不一致");
        }
        $user = User::query()->where("id", UID)->first();
        if (empty($user)) {
            return retFail("该用户不存在");
        }

        $data['salt'] = gen_salt(8); //加盐
        $data['password'] = genPassword($password . $data['salt']);
        $res = User::query()->where("id", UID)->update($data);

        if ($res) {
            return retSuc([], "修改成功");
        } else {
            return retFail("修改失败");
        }
    }
}
